﻿using Core.Tools;
using System;

namespace Core.ObjectOperate.ReflectionImpl
{
    public sealed class ConstructorInfo
    {
        /// <summary>
        /// 创建构造函数
        /// </summary>
        /// <param name="Content">反射构造函数</param>
        /// <returns>返回构造函数</returns>
        public static ConstructorInfo Create(System.Reflection.ConstructorInfo Content)
        {
            return new ConstructorInfo(Content);
        }

        private readonly bool InternalIsPublic;
        private readonly Type[] InternalParamsTypes;
        private readonly Type InternalDeclaringType;
        private readonly IDelegate InternalCtorDelegate;

        private ConstructorInfo(System.Reflection.ConstructorInfo Content)
        {
            if (Content == null)
            {
                throw new NullReferenceException("Content");
            }

            var Params = Content.GetParameters();

            InternalParamsTypes = new Type[Params.Length];

            for (int i = 0; i < Params.Length; i++)
            {
                InternalParamsTypes[i] = Params[i].ParameterType;
            }

            InternalDeclaringType = Content.DeclaringType;

            InternalCtorDelegate = MethodHelper.CreateDelegate(Content);

            InternalIsPublic = Content.IsPublic;
        }

        public Type[] ParamsTypes
        {
            get
            {
                return (Type[])InternalParamsTypes.Clone();
            }
        }

        public object New(object[] Params)
        {
            var Result = TypeHelper.Allocate(InternalDeclaringType);

            InternalCtorDelegate.DynamicInvoke(Result, Params);

            return Result;
        }

        public bool IsPublic
        {
            get
            {
                return InternalIsPublic;
            }
        }

        public Delegate Delegate
        {
            get
            {
                return (Delegate)InternalCtorDelegate;
            }
        }
    }
}